import { Resend } from 'resend';
import config from '../config.js';

// Initialize Resend instance with API key from config
const resend = new Resend(config.resend.RESEND_API_KEY);

/**
 * Send email using Resend
 * @param {string|string[]} to - Recipient email address(es)
 * @param {string} subject - Email subject
 * @param {string} text - Email text content
 * @param {string} [html] - Optional HTML content
 * @returns {Promise} - Result of email sending
 */
async function sendEmail(to, subject, text, html = null) {
  try {
    const emailData = {
      from: config.resend.EMAIL_HOST,
      to,
      subject,
      text,
    };

    // Add HTML content if provided
    if (html) {
      emailData.html = html;
    }

    const response = await resend.emails.send(emailData);
    console.log('Email sent successfully:', response);
    return response;
  } catch (error) {
    console.error('Error sending email:', error);
    throw error;
  }
}

/**
 * Send HTML email using Resend
 * @param {string|string[]} to - Recipient email address(es)
 * @param {string} subject - Email subject
 * @param {string} html - HTML content
 * @returns {Promise} - Result of email sending
 */
async function sendHtmlEmail(to, subject, html) {
  return sendEmail(to, subject, null, html);
}

export {
  sendEmail,
  sendHtmlEmail
};
